﻿using AutoMapper;
using MediatR;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using SY.BasicData.Api.Write.Basic.Applications.Command;
using SY.BasicData.Api.Write.Basic.Applications.Cultivation.Command;
using SY.BasicData.Domain;
using SY.BasicData.Domain.Basic;
using SY.BasicData.ErrorCode;
using SY.BasicData.Infrastructures;
using static Microsoft.EntityFrameworkCore.DbLoggerCategory.Database;

namespace SY.BasicData.Api.Write.Controllers
{
    /// <summary>
    /// 控制器--写
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]

    public class WriteBasicController : ControllerBase
    {
        private readonly IMediator mediator;
        private readonly ILogger<WriteBasicController> logger;
        private readonly IBaseRepository<PictureModel> picRepo;

        public WriteBasicController(IMediator mediator, ILogger<WriteBasicController> logger, IBaseRepository<PictureModel> picRepo)
        {
            this.mediator = mediator;
            this.logger = logger;
            this.picRepo = picRepo;
        }
        /// <summary>
        /// 基本信息添加
        /// </summary>
        /// <param name="command">命令</param>
        /// <returns>返回受影响的行数</returns>
        /// 
        [HttpPost]
        public async Task<ApiResult<int>> AddBasic(AddBasicCommand command)
        {
             
            try
            {
                logger.LogInformation("基本信息添加成功");
                return await mediator.Send(command);
            }
            catch (Exception ex)
            {
                logger.LogInformation("基本信息添加失败"+ex.Message);
                throw;
            }
        }
        /// <summary>
        /// 按生产批次上传“产品检验报告”图片
        /// </summary>
        /// <param name="batch">生产批次</param>
        /// <param name="file">上传的文件</param>
        /// 
        [HttpPost("upload-report")]
        public async Task<IActionResult> UploadReport(string batch, IFormFile file)
        {
            try
            {
                // 1. 参数与业务校验
                if (file == null || string.IsNullOrEmpty(batch))
                    return BadRequest("生产批次和文件不能为空");
                if (!file.ContentType.StartsWith("image/"))
                    return BadRequest("仅支持图片文件");

                // 2. 存储文件到服务器
                string rootPath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "Reports");
                Directory.CreateDirectory(rootPath);
                string fileName = $"{Guid.NewGuid()}{Path.GetExtension(file.FileName)}";
                string fullPath = Path.Combine(rootPath, fileName);
                using (var fileStream = new FileStream(fullPath, FileMode.Create))
                {
                    await file.CopyToAsync(fileStream);
                }
                string fileUrl = $"http://localhost:5124/Reports/{fileName}";

                // 3. 数据库操作（通过仓储）
                var pictureModel = await picRepo.FirstOrDefaultAsync(m => m.Batch == batch);
                if (pictureModel == null)
                {
                    // 创建新的图片路径数组
                    var imagePaths = new List<string> { fileUrl };
                    pictureModel = new PictureModel { Batch = batch, Report = System.Text.Json.JsonSerializer.Serialize(imagePaths) };
                    await picRepo.Add(pictureModel);
                }
                else
                {
                    // 解析现有路径数组，添加新路径
                    List<string> imagePaths;
                    if (string.IsNullOrEmpty(pictureModel.Report))
                    {
                        imagePaths = new List<string>();
                    }//怎么了 不知道啥叫分支你不是让我点全部提交吗然后我点了gitte就显示你提交了个啥分支
                    else
                    {
                        try
                        {
                            imagePaths = System.Text.Json.JsonSerializer.Deserialize<List<string>>(pictureModel.Report) ?? new List<string>();
                        }
                        catch
                        {
                            // 如果解析失败，创建新数组
                            imagePaths = new List<string>();
                        }
                    }
                    
                    // 添加新的图片路径
                    imagePaths.Add(fileUrl);
                    pictureModel.Report = System.Text.Json.JsonSerializer.Serialize(imagePaths);
                    await picRepo.Update(pictureModel);
                }

                return Ok("上传成功，路径已存入数据库");
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "上传失败，批次：{Batch}", batch);
                return StatusCode(500, $"上传失败：{ex.Message}");
            }
        }

        /// <summary>
        /// 通过生产批次移除指定图片路径
        /// </summary>
        /// <param name="batch">生产批次</param>
        /// <param name="imageUrl">要移除的图片URL</param>
        /// <returns>移除结果</returns>
        [HttpDelete("remove-report-image")]
        public async Task<IActionResult> RemoveReportImage(string batch, string imageUrl)
        {
            try
            {
                // 1. 参数验证
                if (string.IsNullOrEmpty(batch))
                    return BadRequest("生产批次不能为空");
                if (string.IsNullOrEmpty(imageUrl))
                    return BadRequest("图片URL不能为空");

                // 2. 查找对应的PictureModel
                var pictureModel = await picRepo.FirstOrDefaultAsync(m => m.Batch == batch);
                if (pictureModel == null)
                {
                    return NotFound($"未找到批次 {batch} 的图片记录");
                }

                // 3. 解析现有的图片路径数组
                List<string> imagePaths;
                if (string.IsNullOrEmpty(pictureModel.Report))
                {
                    return Ok("该批次没有图片记录");
                }

                try
                {
                    imagePaths = System.Text.Json.JsonSerializer.Deserialize<List<string>>(pictureModel.Report) ?? new List<string>();
                }
                catch
                {
                    return BadRequest("图片路径数据格式错误");
                }

                // 4. 查找并移除指定的图片路径
                var originalCount = imagePaths.Count;
                imagePaths.RemoveAll(path => path.Equals(imageUrl, StringComparison.OrdinalIgnoreCase));
                var removedCount = originalCount - imagePaths.Count;

                if (removedCount == 0)
                {
                    return NotFound($"未找到指定的图片路径：{imageUrl}");
                }

                // 5. 更新数据库
                if (imagePaths.Count == 0)
                {
                    // 如果没有剩余图片，清空Report字段
                    pictureModel.Report = string.Empty;
                }
                else
                {
                    // 保存剩余的图片路径
                    pictureModel.Report = System.Text.Json.JsonSerializer.Serialize(imagePaths);
                }

                await picRepo.Update(pictureModel);

                return Ok(new
                {
                    message = $"成功移除 {removedCount} 个图片路径",
                    remainingCount = imagePaths.Count,
                    remainingImages = imagePaths
                });
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "移除图片路径失败，批次：{Batch}，图片URL：{ImageUrl}", batch, imageUrl);
                return StatusCode(500, $"移除图片路径失败：{ex.Message}");
            }
        }

        /// <summary>
        /// 通过生产批次获取所有图片路径
        /// </summary>
        /// <param name="batch">生产批次</param>
        /// <returns>图片路径列表</returns>
        [HttpGet("get-report-images")]
        public async Task<IActionResult> GetReportImages(string batch)
        {
            try
            {
                // 1. 参数验证
                if (string.IsNullOrEmpty(batch))
                    return BadRequest("生产批次不能为空");

                // 2. 查找对应的PictureModel
                var pictureModel = await picRepo.FirstOrDefaultAsync(m => m.Batch == batch);
                if (pictureModel == null)
                {
                    return NotFound($"未找到批次 {batch} 的图片记录");
                }

                // 3. 解析图片路径数组
                List<string> imagePaths = new List<string>();
                if (!string.IsNullOrEmpty(pictureModel.Report))
                {
                    try
                    {
                        imagePaths = System.Text.Json.JsonSerializer.Deserialize<List<string>>(pictureModel.Report) ?? new List<string>();
                    }
                    catch
                    {
                        return BadRequest("图片路径数据格式错误");
                    }
                }

                return Ok(new
                {
                    batch = batch,
                    imageCount = imagePaths.Count,
                    images = imagePaths
                });
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "获取图片路径失败，批次：{Batch}", batch);
                return StatusCode(500, $"获取图片路径失败：{ex.Message}");
            }
        }

        //[HttpPost("upload-report")]
        //public async Task<IActionResult> UploadReport(string batch, IFormFile file)
        //{
        //    // 1. 验证参数
        //    if (file == null || string.IsNullOrEmpty(batch))
        //    {
        //        return BadRequest("生产批次和文件不能为空");
        //    }

        //    // 2. 定义文件存储路径（示例：wwwroot/Reports/）
        //    string rootPath = Directory.GetCurrentDirectory() + "/wwwroot/Reports/";
        //    if (!Directory.Exists(rootPath))
        //    {
        //        Directory.CreateDirectory(rootPath);
        //    }

        //    // 3. 生成唯一文件名（避免重复）
        //    string fileName = $"{Guid.NewGuid()}{Path.GetExtension(file.FileName)}";
        //    string fullPath = Path.Combine(rootPath, fileName);

        //    // 4. 保存文件到服务器
        //    using (var fileStream = new FileStream(fullPath, FileMode.Create))
        //    {
        //        await file.CopyToAsync(fileStream);
        //    }

        //    // 5. 拼接可访问的文件URL（根据实际部署域名/端口调整）
        //    string fileUrl = $"http://localhost:5124/Reports/{fileName}";

        //    // 6. 查找对应生产批次的PictureModel
        //    var pictureModel = await picRepo.GetAll().Where(m => m.Batch == batch).FirstOrDefaultAsync();

        //    if (pictureModel == null)
        //    {
        //        // 如果不存在该批次，可选择创建新记录（根据业务需求）
        //        pictureModel = new PictureModel
        //        {
        //            Batch = batch,
        //            Report = fileUrl // 直接赋值图片URL
        //        };
        //        picRepo.Add(pictureModel);
        //    }
        //    else
        //    {
        //        // 存在则更新Report字段
        //        pictureModel.Report = fileUrl;
        //    }

        //    // 7. 保存数据库更改
        // await picRepo.FirstOrDefaultAsync(m => m.Batch == batch);

        //    return Ok("上传成功，路径已存入数据库");
        //}
        ///// <summary>
        ///// 单图片上传
        ///// </summary>
        ///// <param name="file">文件</param>
        ///// <returns>返回结果</returns>
        ///// 
        //[HttpPost]
        //public IActionResult Upload(IFormFile file)
        //{

        //    string path = Directory.GetCurrentDirectory() + "/wwwroot/Pic/";

        //    string newFileName = Guid.NewGuid().ToString("N") + Path.GetExtension(file.FileName);

        //    using (FileStream fs = new FileStream(path + newFileName, FileMode.Create))
        //    {
        //        file.CopyTo(fs);
        //        fs.Flush();
        //    }

        //    return Ok("http://localhost:5124/Pic/" + newFileName);
        //    ;
        //}

        /// <summary>
        /// 多图片上传
        /// </summary>
        /// <param name="files">文件列表</param>
        /// <returns>返回上传结果</returns>
        [HttpPost]
        public async Task<ApiResult<List<string>>> UploadMultiple(IFormFileCollection files)
        {
            var result = new ApiResult<List<string>>();
            var uploadedUrls = new List<string>();
            
            try
            {
                // 确保上传目录存在
                string uploadPath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "Pic");
                if (!Directory.Exists(uploadPath))
                {
                    Directory.CreateDirectory(uploadPath);
                }

                // 验证文件数量限制
                if (files == null || files.Count == 0)
                {
                    result.Code = ApiEnum.Fail;
                    result.Message = "没有选择要上传的文件";
                    return result;
                }

                // 限制上传文件数量（可根据需要调整）
                const int maxFileCount = 10;
                if (files.Count > maxFileCount)
                {
                    result.Code = ApiEnum.Fail;
                    result.Message = $"最多只能上传{maxFileCount}个文件";
                    return result;
                }

                // 限制单个文件大小（5MB）
                const long maxFileSize = 5 * 1024 * 1024;
                var allowedExtensions = new[] { ".jpg", ".jpeg", ".png", ".gif", ".bmp" };

                foreach (var file in files)
                {
                    // 验证文件大小
                    if (file.Length > maxFileSize)
                    {
                        result.Code = ApiEnum.Fail;
                        result.Message = $"文件 {file.FileName} 超过5MB大小限制";
                        return result;
                    }

                    // 验证文件扩展名
                    var fileExtension = Path.GetExtension(file.FileName).ToLowerInvariant();
                    if (!allowedExtensions.Contains(fileExtension))
                    {
                        result.Code = ApiEnum.Fail;
                        result.Message = $"文件 {file.FileName} 格式不支持，仅支持：{string.Join(", ", allowedExtensions)}";
                        return result;
                    }

                    // 生成唯一文件名
                    string newFileName = Guid.NewGuid().ToString("N") + fileExtension;
                    string filePath = Path.Combine(uploadPath, newFileName);

                    // 保存文件
                    using (var stream = new FileStream(filePath, FileMode.Create))
                    {
                        await file.CopyToAsync(stream);
                    }

                    // 添加到结果列表
                    string fileUrl = $"http://localhost:5124/Pic/{newFileName}";
                    uploadedUrls.Add(fileUrl);
                }

                result.Code = ApiEnum.Success;
                result.Message = $"成功上传 {uploadedUrls.Count} 个文件";
                result.Data = uploadedUrls;
                
                logger.LogInformation($"多图片上传成功，共上传 {uploadedUrls.Count} 个文件");
            }
            catch (Exception ex)
            {
                result.Code = ApiEnum.Fail;
                result.Message = "多图片上传失败：" + ex.Message;
                logger.LogError(ex, "多图片上传失败");
            }

            return result;
        }
        /// <summary>
        /// 基本信息修改
        /// </summary>
        /// <param name="command">命令</param>
        /// <returns>返回受影响的行数</returns>
        /// 
        [HttpPost]
        public async Task<ApiResult<int>> UpdateBasic( UpdateBasicCommand command)
        {
            try
            {
                logger.LogInformation("基本信息修改成功");
                return await mediator.Send(command);
            }
            catch (Exception ex)
            {
                logger.LogInformation("基本信息修改失败" + ex.Message);
                throw;
            }

        }
        /// <summary>
        /// 基本信息批量删除
        /// </summary>
        /// <param name="command">命令</param>
        /// <returns>返回受影响的行数</returns>
        /// 
        [HttpPut]
        public async Task<ApiResult<int>> DelRangeBasic(DelRangBaseCommand command)
        {
            try
            {
                logger.LogInformation("基本信息删除成功");
                return await mediator.Send(command);
            }
            catch (Exception ex)
            {
                logger.LogInformation("基本信息删除失败" + ex.Message);
                throw;
            }
        }

        ///// <summary>
        ///// 获取图片列表
        ///// </summary>
        ///// <param name="batch">批次号（可选）</param>
        ///// <returns>返回图片URL列表</returns>
        //[HttpGet]
        //public ApiResult<List<string>> GetImageList(string batch = null)
        //{
        //    var result = new ApiResult<List<string>>();

        //    try
        //    {
        //        string picPath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "Pic");
        //        var imageUrls = new List<string>();

        //        if (Directory.Exists(picPath))
        //        {
        //            var allowedExtensions = new[] { ".jpg", ".jpeg", ".png", ".gif", ".bmp" };
        //            var files = Directory.GetFiles(picPath)
        //                .Where(f => allowedExtensions.Contains(Path.GetExtension(f).ToLowerInvariant()))
        //                .OrderBy(f => f)
        //                .ToList();

        //            foreach (var file in files)
        //            {
        //                var fileName = Path.GetFileName(file);
        //                var imageUrl = $"http://localhost:5124/Pic/{fileName}";
        //                imageUrls.Add(imageUrl);
        //            }
        //        }

        //        result.Code = ApiEnum.Success;
        //        result.Message = "获取图片列表成功";
        //        result.Data = imageUrls;

        //        logger.LogInformation($"获取图片列表成功，共{imageUrls.Count}张图片");
        //    }
        //    catch (Exception ex)
        //    {
        //        result.Code = ApiEnum.Fail;
        //        result.Message = "获取图片列表失败：" + ex.Message;
        //        logger.LogError(ex, "获取图片列表失败");
        //    }

        //    return result;
        //}
        /// <summary>
        /// 图片反填
        /// </summary>
        /// <param name="command">命令</param>
        /// <returns>返回结果</returns>
        /// 
        [HttpGet]
        public Task<ApiResult<PictureModel>> GetPic([FromQuery] GetPicQueryCommand command)
        {
            return mediator.Send(command);
          
        }
        /// <summary>
        /// 图片添加
        /// </summary>
        /// <param name="command">命令</param>
        /// <returns>返回结果</returns>
        /// 
        [HttpPost]
        public async Task<ApiResult<int>> AddPic(AddPicQueryCommand command)
        {
            return await mediator.Send(command);
        }
        /// <summary>
        /// 免疫信息修改
        /// </summary>
        /// <param name="command">命令</param>
        /// <returns>返回结果</returns>
        /// 
        [HttpPut]
        public async Task<ApiResult<int>> UpdateImmunity(UpdateImmunityCommand command)
        {
            return await  mediator.Send(command);
        }

        /// <summary>
        /// 获取图片列表（可按批次/关键字过滤）
        /// </summary>
        /// <param name="batch">批次号或关键字（可选）</param>
        /// <returns>图片URL列表</returns>
        [HttpGet]
        public ApiResult<List<string>> GetImageList(string? batch = null)
        {
            var result = new ApiResult<List<string>>();
            var imageUrls = new List<string>();

            try
            {
                string picPath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "Pic");
                if (!Directory.Exists(picPath))
                {
                    result.Code = ApiEnum.Fail;
                    result.Message = "图片目录不存在";
                    return result;
                }

                var allowedExtensions = new[] { ".jpg", ".jpeg", ".png", ".gif", ".bmp" };
                var files = Directory.GetFiles(picPath)
                    .Where(f => allowedExtensions.Contains(Path.GetExtension(f).ToLowerInvariant()))
                    .OrderBy(f => f)
                    .ToList();

                if (!string.IsNullOrWhiteSpace(batch))
                {
                    files = files
                        .Where(f => Path.GetFileName(f).Contains(batch, StringComparison.OrdinalIgnoreCase))
                        .ToList();
                }

                foreach (var file in files)
                {
                    var fileName = Path.GetFileName(file);
                    var imageUrl = $"http://localhost:5124/Pic/{fileName}";
                    imageUrls.Add(imageUrl);
                }

                result.Code = ApiEnum.Success;
                result.Message = "获取图片列表成功";
                result.Data = imageUrls;
                logger.LogInformation($"获取图片列表成功，共{imageUrls.Count}张图片");
            }
            catch (Exception ex)
            {
                result.Code = ApiEnum.Fail;
                result.Message = "获取图片列表失败：" + ex.Message;
                logger.LogError(ex, "获取图片列表失败");
            }

            return result;
        }

        /// <summary>
        /// 批量删除图片（支持文件名或完整URL）
        /// </summary>
        /// <param name="fileNamesOrUrls">文件名或URL列表</param>
        /// <returns>已删除数量</returns>
        [HttpDelete]
        public ApiResult<int> DeleteImages([FromBody] List<string> fileNamesOrUrls)
        {
            var result = new ApiResult<int>();

            try
            {
                if (fileNamesOrUrls == null || fileNamesOrUrls.Count == 0)
                {
                    result.Code = ApiEnum.Fail;
                    result.Message = "未提供要删除的文件";
                    return result;
                }

                string picPath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "Pic");
                int deleted = 0;

                foreach (var item in fileNamesOrUrls)
                {
                    string fileName = item;
                    if (Uri.TryCreate(item, UriKind.Absolute, out var uri))
                    {
                        fileName = Path.GetFileName(uri.LocalPath);
                    }
                    else
                    {
                        fileName = Path.GetFileName(item);
                    }

                    string fullPath = Path.Combine(picPath, fileName);
                    if (System.IO.File.Exists(fullPath))
                    {
                        System.IO.File.Delete(fullPath);
                        deleted++;
                    }
                }

                result.Code = ApiEnum.Success;
                result.Message = deleted > 0 ? $"成功删除 {deleted} 个文件" : "未删除任何文件";
                result.Data = deleted;
                logger.LogInformation(result.Message);
            }
            catch (Exception ex)
            {
                result.Code = ApiEnum.Fail;
                result.Message = "删除图片失败：" + ex.Message;
                logger.LogError(ex, "删除图片失败");
            }

            return result;
        }
    }
}
